from rest_framework.viewsets import ViewSet
from users.models import User
from rest_framework.decorators import action
from django.utils import timezone
from rest_framework.response import Response
from datetime import timedelta
import pytz
from django.conf import settings
from goods.models import GoodsVisitCount
from meiduo_admin.serializer.home_serializers import GoodsDaySerializer
from rest_framework.permissions import IsAdminUser


# statistical/total_count/
class HomeViewSet(ViewSet):

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    @action(methods=['get'], detail=False)
    def total_count(self, request):
        # 获得用户总数量
        count = User.objects.count()
        # timezone.now() -->  当前时间（上海2019-7-11 9:45:56）
        # print(timezone.now()) -->  UTC时区： 2019-07-11 01:54:42.998445+00:00
        # 时间：年月日，十分秒，时区
        # 我如何才能够获取当前上海时间的零点 2019-7-11 0：0：0 Shanghai
        # d:  2019-07-11 20:27:48 + 08:00
        # replace(hour=0, minute=0, second=0)吧时间改成  2019-07-11 0:0:0+ 08:00
        # d = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(hour=0, minute=0, second=0)
        # print('d: ', d)

        # 获得当天日期
        # .now() 获取年月日时分秒
        # .data() 只获取年月日
        data = timezone.now().date()
        return Response({
            'count': count,
            'data': data
        })

    # 请求方式： GET /meiduo_admin/statistical/day_increment/
    @action(methods=['get'], detail=False)
    def day_increment(self, request):
        # 1.获取当日的零时
        # timezone.now()获得当前时间.astimezone(settings.TIME_ZONE))转换成上海时间.replace(hour=0, minute=0, second=0)获得上海时区的0:0:0
        date_0_shanghai = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(hour=0, minute=0, second=0)
        # 2.根据零时,过滤用户
        count = User.objects.filter(date_joined__gte=date_0_shanghai).count()
        # 3.构建响应数据
        return Response({
            'count': count,
            'date': date_0_shanghai.date()
        })

    # 请求方式：GET / meiduo_admin / statistical / day_active /
    @action(methods=['get'], detail=False)
    def day_active(self, request):
        # 1.获取当日零时
        date_0_shanghai = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(hour=0, minute=0, second=0)
        # 2.过滤用户
        count = User.objects.filter(date_joined__gte=date_0_shanghai).count()
        # 3.统计数据,构建返回
        return Response({
            'count': count,
            'date': date_0_shanghai.date()
        })

    # 请求方式：GET /meiduo_admin/statistical/day_orders/
    @action(methods=['get'], detail=False)
    def day_orders(self, request):
        # 统计日下单用户
        date_0_shanghai = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(hour=0, minute=0, second=0)

        # 从主表入手
        user_queryset = User.objects.filter(orderinfo__create_time__gte=date_0_shanghai)
        # 去重
        count = len(set(user_queryset))

        return Response({
            'count': count,
            'date': date_0_shanghai.date()
        })

    # 请求方式：GET /meiduo_admin/statistical/month_increment/
    @action(methods=['get'], detail=False)
    def month_increment(self, request):
        # 获得现在的时间
        cur_date = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE))
        # 现在的时间减去29天
        start_date = cur_date - timedelta(days=29)

        date_list = []
        for index in range(30):
            # 每遍历一次，获得一个当日的时间（零时）
            # index: 0              1                   2
            # 开始时间： start_date   start_date + 1天    start_date + 2天
            clac_date = (start_date + timedelta(days=index)) \
                .replace(hour=0, minute=0, second=0)

            # 过滤用户
            count = User.objects.filter(date_joined__gte=clac_date,
                                        date_joined__lt=clac_date+timedelta(days=1)).count()

            date_list.append({
                'count': count,
                'date': clac_date.date()
            })

        return Response(date_list)

    # 请求方式： GET /meiduo_admin/statistical/goods_day_views/
    @action(methods=['get'], detail=False)
    def goods_day_views(self, request):
        # 1.获得序列化数据GoodsVisitCount
        date_0_shanghai = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE)).replace(hour=0, minute=0, second=0)
        serializer = GoodsVisitCount.objects.filter(create_time__gte=date_0_shanghai)
        # 2.调用序列化器完成数据序列化
        serializer1 = GoodsDaySerializer(serializer, many=True)
        # 3.构建响应对象
        return Response(serializer1.data)